package com.cyy.daijia.map.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.cyy.daijia.common.constant.RedisConstant;
import com.cyy.daijia.common.constant.SystemConstant;
import com.cyy.daijia.common.util.LocationUtil;
import com.cyy.daijia.driver.client.DriverInfoFeignClient;
import com.cyy.daijia.map.repository.OrderServiceLocationRepository;
import com.cyy.daijia.map.service.LocationService;
import com.cyy.daijia.model.entity.driver.DriverSet;
import com.cyy.daijia.model.entity.map.OrderServiceLocation;
import com.cyy.daijia.model.form.map.OrderServiceLocationForm;
import com.cyy.daijia.model.form.map.SearchNearByDriverForm;
import com.cyy.daijia.model.form.map.UpdateDriverLocationForm;
import com.cyy.daijia.model.form.map.UpdateOrderLocationForm;
import com.cyy.daijia.model.vo.map.NearByDriverVo;
import com.cyy.daijia.model.vo.map.OrderLocationVo;
import com.cyy.daijia.model.vo.map.OrderServiceLastLocationVo;
import com.cyy.daijia.order.client.OrderInfoFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class LocationServiceImpl implements LocationService {
    private final RedisTemplate redisTemplate;
    private final DriverInfoFeignClient driverInfoFeignClient;
    private final OrderServiceLocationRepository orderServiceLocationRepository;
    private final MongoTemplate mongoTemplate;
    private final OrderInfoFeignClient orderInfoFeignClient;

    /*key：地理空间集合的名称（类似于一个数据库表的名字）。
    longitude：地点的经度。
    latitude：地点的纬度。
    member：地点的标识符或名称。*/
    @Override
    public Boolean updateDriverLocation(UpdateDriverLocationForm updateDriverLocationForm) {
        Point point = new Point(updateDriverLocationForm.getLongitude().doubleValue(), updateDriverLocationForm.getLatitude().doubleValue());
        //用有用户id作为地点信息标识
        //往redis存储long数据时用string存储
        redisTemplate.opsForGeo().add(RedisConstant.DRIVER_GEO_LOCATION,point, updateDriverLocationForm.getDriverId().toString());
        return true;
    }

    @Override
    public Boolean removeDriverLocation(Long driverId) {
        redisTemplate.opsForGeo().remove(RedisConstant.DRIVER_GEO_LOCATION, driverId.toString());
        return true;
    }

    @Override
    public List<NearByDriverVo> searchNearByDriver(SearchNearByDriverForm searchNearByDriverForm) {
        // 搜索经纬度位置5公里以内的司机
        //定义经纬度点
        Point point = new Point(searchNearByDriverForm.getLongitude().doubleValue(), searchNearByDriverForm.getLatitude().doubleValue());
        //定义距离：5公里(系统配置)
        Distance distance = new Distance(SystemConstant.NEARBY_DRIVER_RADIUS, RedisGeoCommands.DistanceUnit.KILOMETERS);
        //定义以point点为中心，distance为距离这么一个范围
        Circle circle = new Circle(point, distance);

        //定义GEO参数
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance() //包含距离
                .includeCoordinates() //包含坐标
                .sortAscending(); //排序：升序

        // 1.GEORADIUS获取附近范围内的信息
        GeoResults<RedisGeoCommands.GeoLocation<String>> result = this.redisTemplate.opsForGeo().radius(RedisConstant.DRIVER_GEO_LOCATION, circle, args);

        //2.收集信息，存入list
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = result.getContent();

        //3.返回计算后的信息
        List<NearByDriverVo> list = new ArrayList();
        if(!CollectionUtils.isEmpty(content)) {
            Iterator<GeoResult<RedisGeoCommands.GeoLocation<String>>> iterator = content.iterator();
            while (iterator.hasNext()) {
                GeoResult<RedisGeoCommands.GeoLocation<String>> item = iterator.next();

                //司机id
                Long driverId = Long.parseLong(item.getContent().getName());
                //当前距离
                BigDecimal currentDistance = new BigDecimal(item.getDistance().getValue()).setScale(2, RoundingMode.HALF_UP);
                log.info("司机：{}，距离：{}",driverId, item.getDistance().getValue());

                //获取司机接单设置参数
                DriverSet driverSet = driverInfoFeignClient.getDriverSet(driverId).getData();
                //接单里程判断，acceptDistance==0：不限制，
                if(driverSet.getAcceptDistance().doubleValue() != 0 && driverSet.getAcceptDistance().subtract(currentDistance).doubleValue() < 0) {
                    continue;
                }
                //订单里程判断，orderDistance==0：不限制
                if(driverSet.getOrderDistance().doubleValue() != 0 && driverSet.getOrderDistance().subtract(searchNearByDriverForm.getMileageDistance()).doubleValue() < 0) {
                    continue;
                }

                //满足条件的附近司机信息
                NearByDriverVo nearByDriverVo = new NearByDriverVo();
                nearByDriverVo.setDriverId(driverId);
                nearByDriverVo.setDistance(currentDistance);
                list.add(nearByDriverVo);
            }
        }
        return list;
    }

    @Override
    public Boolean updateOrderLocationToCache(UpdateOrderLocationForm updateOrderLocationForm) {
        OrderLocationVo orderLocationVo = new OrderLocationVo();
        orderLocationVo.setLatitude(updateOrderLocationForm.getLatitude());
        orderLocationVo.setLongitude(updateOrderLocationForm.getLongitude());
        String key=RedisConstant.UPDATE_ORDER_LOCATION + updateOrderLocationForm.getOrderId();
        redisTemplate.opsForValue().set(key, orderLocationVo);
        return true;
    }

    @Override
    public OrderLocationVo getCacheOrderLocation(Long orderId) {
        String key=RedisConstant.UPDATE_ORDER_LOCATION + orderId;
        return (OrderLocationVo)redisTemplate.opsForValue().get(key);
    }

    @Override
    public Boolean saveOrderServiceLocation(List<OrderServiceLocationForm> orderLocationServiceFormList) {
        List<OrderServiceLocation> orderServiceLocations=new ArrayList<>();
        orderLocationServiceFormList.forEach(orderServiceLocationForm -> {
            OrderServiceLocation orderServiceLocation = BeanUtil.copyProperties(orderServiceLocationForm, OrderServiceLocation.class);
            orderServiceLocation.setId(ObjectId.get().toString());
            orderServiceLocation.setCreateTime(new Date());
                }
        );
        //执行sql语句时减小于数据库连接次数
        orderServiceLocationRepository.saveAll(orderServiceLocations);
        return true;
    }

    @Override
    public OrderServiceLastLocationVo getOrderServiceLastLocation(Long orderId) {
        /*orderServiceLocationRepository.findOne(new Example<OrderServiceLocation>() {
        })*/

        Query query = new Query();
        query.addCriteria(Criteria.where("orderId").is(orderId));
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        //orderServiceLocationRepository.findOne();
        OrderServiceLocation orderServiceLocation = mongoTemplate.findOne(query, OrderServiceLocation.class);
        return BeanUtil.copyProperties(orderServiceLocation, OrderServiceLastLocationVo.class);
    }

    @Override
    public BigDecimal calculateOrderRealDistance(Long orderId) {
        /*OrderServiceLocation orderServiceLocation = new OrderServiceLocation();
        orderServiceLocation.setOrderId(orderId);
        Example<OrderServiceLocation> example = Example.of(new OrderServiceLocation());
        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
        //从mongdb获取根据订单id
        List<OrderServiceLocation> orderServiceLocationList = orderServiceLocationRepository.findAll(example, sort);*/
        double res=0;
        List<OrderServiceLocation> orderServiceLocationList = orderServiceLocationRepository.findByOrderIdOrderByCreateTimeAsc(orderId);
        if(!CollUtil.isEmpty(orderServiceLocationList)){

            int size=orderServiceLocationList.size();
            for(int i=0;i<size-1;i++){
                OrderServiceLocation begin = orderServiceLocationList.get(i);
                OrderServiceLocation end = orderServiceLocationList.get(i + 1);
                double distance = LocationUtil
                        .getDistance(begin.getLatitude().doubleValue(), begin.getLongitude().doubleValue(), end.getLatitude().doubleValue(), end.getLongitude().doubleValue());
                res+=distance;
            }
        }
        //测试过程中，没有真正代驾，实际代驾GPS位置没有变化，模拟：实际代驾里程 = 预期里程 + 5
        if(res == 0) {
            return orderInfoFeignClient.getOrderInfo(orderId).getData().getExpectDistance().add(new BigDecimal("5"));
        }
        //遍历数据，利用工具类计算里程
        return new BigDecimal(res);
    }
}
